import random
import re
import string
from datetime import datetime, timedelta, time
from time import sleep
import json
from dao.mqtthelp_v2 import MQTTClient
from utils.config import Config

# 生成每个雷达设备的车辆数据,更真实的场景数据
def creatRealData(list, num_devices,lane,car_startnum,car_endnum):
    all_real_vehicle_data = []
    current_time = datetime.now()

    for i in range(num_devices):
        location = list[i][0]
        device_num = list[i][3]
        timestamp_milliseconds = current_time.strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]  # 毫秒级

        num_vehicles = random.randint(car_startnum,car_endnum)  # 每个设备随机生成车辆数
        objects_list = []

        for j in range(num_vehicles):
            vehicle_data = {
                "ID": j + 1,
                "x": -320,  # x坐标
                "y": 15000,  # y坐标
                "v_x": 0,  # x轴速度
                "v_y": -2120,  # y轴速度
                "length": 480,
                "width": 190,
                "height": 170,
                "type": random.randint(0, 2),  # 随机生成车辆类型
                # #目标类型：0 小型客车,1 中型客车,2 大型客车,3 小型货车,4 中型货车,5 重型货车,6 警
                #车,7 救护车,8 消防车,9 校车,10 工程车,11 危化品车,12 三轮车,13 摩托车,14 自行车,15
                #行人,16 动物,17 工作人员,100 其他
                "class": 1,#random.randint(0, 11),  # 随机生成车辆类别   15以后的不识别
                "color": 2,
                "plate_color": 7,#random.randint(6, 7),  # 随机生成车牌颜色   0 白,1 灰,2 黄,3 粉,4 红,5 紫,6 绿,7 蓝,8 棕,9 黑,100 其他
                "lane": lane,#random.randint(1, 3),  # 随机选择车道
                "lane_dir": 1,  # 车道方向
                "km_dir": 1,
                "event": 0,
                "plate": #"湘A12345",
                    "粤" + random.choice(string.ascii_uppercase[:8]) +''.join(random.choices(string.ascii_uppercase + string.digits, k=5)),
                # 生成随机车牌号：湘A-H + 5位数字或大写字母
                "stake_mark": list[i][0],
                "longitude": list[i][1],
                "latitude": list[i][2],
                "altitude": 45.00,
                "speed": round(random.uniform(0, 100), 2),  # 随机生成速度
                "heading": 49.23  # 随机生成车头方向
            }

            objects_list.append(vehicle_data)

        device_data = {
            "location": location,
            "device_num": device_num,
            "timestamp": timestamp_milliseconds,
            "number": num_vehicles,
            "objects_list": objects_list
        }

        all_real_vehicle_data.append(device_data)
    return all_real_vehicle_data

# 模拟并发场景，每一个雷达数据发完后往后一个雷达传递参数，车牌不变，调整桩号，设备、时间，速度、车道取随机数；每个雷达随机发送(s-e)次
# path是线路   device是设备名
def publishpath(path,path2,n,lane,s,e,car_startnum,car_endnum):
    all_vehicle_data1 = creatRealData(path, len(path),lane,car_startnum,car_endnum)
    all_vehicle_data2 = creatRealData(path2, len(path),lane,car_startnum,car_endnum)

    for _ in range(n):
        for k in range(random.randint(s,e)):
            all_vehicle_data=all_vehicle_data1+all_vehicle_data2
            mqtt_client.concurrent_publish('bizdata/objects_list', all_vehicle_data)
            print(all_vehicle_data)
            sleep(0.5)
            current_time = datetime.now().strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]
            for l in range(len(all_vehicle_data1)):
                all_vehicle_data1[l]['timestamp'] = current_time
                for objects in all_vehicle_data1[l]['objects_list']:     #模拟同一个雷视同一车辆报的车辆的stake_mark每次往前加10米
                    objects['stake_mark']= re.sub(r'(\w{2}\d)(\+\d{2,3})', lambda x: x.group(1) + "+" + str(int(x.group(2)[1:]) + 10*(k+1)).zfill(len(x.group(2)) - 1), all_vehicle_data1[l]['location'])
                    #objects['longitude']= round(float(objects['longitude'])+round(float(objects['speed']/3600/111*0.5), 8),8)

        data_length = len(all_vehicle_data1)
        for j in range(data_length - 1):
            current_time = datetime.now().strftime("%Y/%m/%d-%H:%M:%S.%f")[:-3]
            all_vehicle_data1[j]['location'] = all_vehicle_data1[j + 1]['location']
            all_vehicle_data1[j]['device_num'] = all_vehicle_data1[j + 1]['device_num']
            all_vehicle_data1[j]['timestamp'] = current_time
            for obj in all_vehicle_data1[j]['objects_list']:
                obj['lane'] =lane  #random.choices([5, 6], [0.9, 0.1], k=1)[0]
                obj['stake_mark'] = path[j + 1][0]
                obj['longitude'] = path[j + 1][1]
                obj['latitude'] = path[j + 1][2]
                obj['speed'] = round(random.uniform(0, 100), 2)
        all_vehicle_data1 = creatRealData(path, 1,lane,car_startnum,car_endnum) + all_vehicle_data1[:-1]


config = Config('./conf/config.ini')
nanxian_main=config.read_value('leishi', 'nanxian_main')
nanxian_zhuru =config.read_value('leishi', 'nanxian_zhuru')
nanxian_zharu =config.read_value('leishi', 'nanxian_zharu')
nanxian_zhuchu=config.read_value('leishi', 'nanxian_zhuchu')
nanxian_zhachu=config.read_value('leishi', 'nanxian_zhachu')

beixian_main = config.read_value('leishi', 'beixian_main')
beixian_zhuru=config.read_value('leishi', 'beixian_zhuru')
beixian_zharu=config.read_value('leishi', 'beixian_zharu')
beixian_zhuchu=config.read_value('leishi', 'beixian_zhuchu')
beixian_zhachu=config.read_value('leishi', 'beixian_zhachu')

nanxian_path=nanxian_zhuru + ',' + nanxian_main + ',' + nanxian_zhuchu + ',' +nanxian_zharu+ ',' +nanxian_zhachu
beixian_path=beixian_zhuru + ',' + beixian_main + ',' + beixian_zhuchu + ',' +beixian_zharu+ ',' +beixian_zhachu
jingweidu_list=eval(config.read_value('jingweidu', 'RC031lane_5')+ ',' +config.read_value('jingweidu', 'RC030lane_5')+ ',' +config.read_value('jingweidu', 'RC029lane_5')+ ',' +config.read_value('jingweidu', 'RC028lane_5')+ ',' +config.read_value('jingweidu', 'RC025lane_5')+ ',' +config.read_value('jingweidu', 'RC024lane_5')+ ',' +config.read_value('jingweidu', 'RC023lane_5')+ ',' +config.read_value('jingweidu', 'RC022lane_5')+ ',' +config.read_value('jingweidu', 'RC021lane_5')+ ',' +config.read_value('jingweidu', 'RC020lane_5')+ ',' +config.read_value('jingweidu', 'RC019lane_5')+ ',' +config.read_value('jingweidu', 'RC018lane_5')+ ',' +config.read_value('jingweidu', 'RC017lane_5')+ ',' +config.read_value('jingweidu', 'RC016lane_5')+ ',' +config.read_value('jingweidu', 'RC015lane_5')+ ',' +config.read_value('jingweidu', 'RC014lane_5')+ ',' +config.read_value('jingweidu', 'RC013lane_5')+ ',' +config.read_value('jingweidu', 'RC012lane_5')+ ',' +config.read_value('jingweidu', 'RC008lane_5')+ ',' +config.read_value('jingweidu', 'RC007lane_5')+ ',' +config.read_value('jingweidu', 'RC006lane_5')+ ',' +config.read_value('jingweidu', 'RC005lane_5')+ ',' +config.read_value('jingweidu', 'RC004lane_5')+ ',' +config.read_value('jingweidu', 'RC003lane_5')+ ',' +config.read_value('jingweidu', 'RC002lane_5')+ ',' +config.read_value('jingweidu', 'RC001lane_5'))

# 实例化 MQTTClient
mqtt_client = MQTTClient()
path = nanxian_zhuru + ',' + nanxian_main + ',' + nanxian_zhuchu
path2= nanxian_zharu+ ',' + nanxian_zhachu + ',' + beixian_path
path_list1=eval(path)
path_list2=eval(path2)
# 参数分别是  模拟线路/其他设备/车往后走几个桩位/车道/同一个雷达报同一车牌开始数/同一个雷达报同一车牌结束数/随机模拟车最小车辆数量/随机模拟车最大车辆数量（其他路线只是为了模拟更真实的场景）
publishpath(path_list1,path_list2,200000,3,8,15,2,5)

